package com.psychologyCommunity.Community.service;
import com.psychologyCommunity.Community.dao.CommentMapper;
import com.psychologyCommunity.Community.entity.Comment;
import com.psychologyCommunity.Community.util.CommunityConstance;
import com.psychologyCommunity.Community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

import static com.psychologyCommunity.Community.util.CommunityConstance.ENTITY_TYPE_POST;

@Service
public class CommentService implements CommunityConstance {
    @Autowired
   private CommentMapper commentMapper;

    public List<Comment> findCommentsByEntity(int entityType,int entityId,int offset,int limit){
       return  commentMapper.selectCommentsByEntity(entityType,entityId,offset,limit);
    }
    public  int findCountByEntity(int entityType,int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private  DiscussPostService discussPostService;
    //添加评论，因为这个里面包含两次dml操作，所以 希望对它进行事务管理--保证这两次操作在一次事务操作内，要么一次成功要么都失败
    //整个方法在一个事务范围之内，并不是局部，所以用声明式事务 加个注解就行了
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment==null){ //要先做一个非空判断
            throw new IllegalArgumentException("参数不能为空!");
        }
        //在加入评论之前 也要对评论进行敏感词过滤 ，所以过滤器的组件也得先注入
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));//首先过滤的是标签，传入的是过滤前的内容
        comment.setContent(sensitiveFilter.filter(comment.getContent()));//过滤敏感词
        //处理完之后 就可以插入操作了 -最终会返回插入的行数 一般就是1
        int rows = commentMapper.insertComment(comment);
        //更新帖子的评论数 ,如果评论的是帖子 就更新帖子的数量
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            //那么我拿到 评论表中的数量 ，然后更新帖子表里面的comment_count 评论数量列
            int count=commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),count);//更新为最新值
        }
        return rows;
    }
    public Comment findCommentById(int id){
        return commentMapper.selectCommentById(id);
    }
}
